# coding:utf-8
# ui/community_comparer.py

from PyQt5.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, QComboBox, QTextEdit
from PyQt5.QtGui import QFont
from analysis.evaluation import precision_recall_fscore
import os


class CommunityComparer(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.init_ui()

    def init_ui(self):
        layout = QVBoxLayout(self)

        title = QLabel("社区对比分析", self)
        title.setFont(QFont('Arial', 24, QFont.Bold))
        layout.addWidget(title)

        # 下拉选择两个社区
        top_layout = QHBoxLayout()
        self.combo1 = QComboBox(self)
        self.combo2 = QComboBox(self)
        self.load_community_ids()

        top_layout.addWidget(QLabel("社区1："))
        top_layout.addWidget(self.combo1)
        top_layout.addWidget(QLabel("社区2："))
        top_layout.addWidget(self.combo2)
        layout.addLayout(top_layout)

        # 对比按钮
        compare_btn = QPushButton("对比这两个社区", self)
        compare_btn.clicked.connect(self.compare_selected_communities)
        layout.addWidget(compare_btn)

        # 输出文本框
        self.result_area = QTextEdit(self)
        self.result_area.setReadOnly(True)
        layout.addWidget(self.result_area)

        # 返回按钮
        back_btn = QPushButton("返回主界面", self)
        back_btn.clicked.connect(lambda: self.parent().switch_page(0))
        layout.addWidget(back_btn)

        self.setLayout(layout)

    def load_community_ids(self):
        community_dir = "results/communities"
        if not os.path.exists(community_dir):
            self.combo1.addItem("未找到社区")
            self.combo2.addItem("未找到社区")
            return

        files = [f.replace("lama_community_", "").replace(".txt", "") for f in os.listdir(community_dir)]
        for f in files:
            self.combo1.addItem(f)
            self.combo2.addItem(f)

    def compare_selected_communities(self):
        id1 = self.combo1.currentText()
        id2 = self.combo2.currentText()

        community1 = self._load_community(id1)
        community2 = self._load_community(id2)

        r, p, f, j = precision_recall_fscore(community1, community2)

        result = f"社区 {id1} vs {id2}\n"
        result += f"Recall: {r:.4f}\n"
        result += f"Precision: {p:.4f}\n"
        result += f"F1-score: {f:.4f}\n"
        result += f"Jaccard Index: {j:.4f}"
        self.result_area.setText(result)

    def _load_community(self, community_id):
        file_path = f"results/communities/lama_community_{community_id}.txt"
        if not os.path.exists(file_path):
            return []
        with open(file_path, 'r') as f:
            return [int(line.strip()) for line in f]